import { dest, src } from "gulp"
import path from "path"
import dartSass from "sass"
import gulpSass from "gulp-sass"
// import autoprefixer from 'gulp-autoprefixer'
import autoprefixer from "autoprefixer"
import cleanCSS from "gulp-clean-css"
import { rollup } from "rollup"
import esbuild from "rollup-plugin-esbuild"
import glob from "fast-glob"
import {
  root,
  pkgRoot,
  output,
  outputEsm,
  outputCjs,
  outputTheme,
  outputDist,
} from "../utils/paths"
import { generatePaths } from "../utils/rollup"
import sourcemaps from "gulp-sourcemaps"
import postcss from "gulp-postcss"
import rename from "gulp-rename"
import filter from "gulp-filter"
import fs from "fs"
//复制scss源文件到 src目录
async function copyThemeChalkSource() {
  await new Promise((resolve) => {
    src("theme-chalk/**/*.scss", { cwd: pkgRoot })
      .pipe(dest(path.resolve(outputTheme, "src")))
      .on("end", resolve)
  })
}

//复制package.json文件到 打包目录
async function copyPackageAndPgMd() {
  await new Promise((resolve) => {
    src(["README.md"], { cwd: root }).pipe(dest(output)).on("end", resolve)

    const data = fs.readFileSync(path.resolve(root, "package.json"))
    let jsonData = JSON.parse(data)
    Object.assign(jsonData, { private: false })
    delete jsonData.workspaces
    delete jsonData.scripts

    const updatedData = JSON.stringify(jsonData, null, 2)
    fs.mkdir(output, (err) => {
      if (err) {
        console.error(err);
      } else {
        fs.writeFileSync(path.resolve(output, "package.json"), updatedData)
      }
    })
  })
}
//构建scss
async function buildScss() {
  const sass = gulpSass(dartSass)
  await new Promise((resolve) => {
    const f1 = filter(["*/index.css", "*/index.css.map"], { restore: true })
    src("theme-chalk/**/*.scss", { cwd: pkgRoot })
      .pipe(sourcemaps.init())
      .pipe(sass().on("error", sass.logError))
      .pipe(
        postcss([
          autoprefixer({
            //兼容哪些版本浏览器
            cascade: true,
            remove: true,
          }),
        ])
      )
      .pipe(cleanCSS())
      .pipe(
        rename((path, bb) => {
          if (path.basename !== "index") {
            path.basename = `jzt-${path.basename}`
          }
        })
      )
      .pipe(sourcemaps.write("."))
      .pipe(f1)
      .pipe(dest(outputDist))
      .pipe(f1.restore)
      .pipe(dest(outputTheme))
      .on("end", resolve)
  })
}

//复制index.css源文件到 dist目录
async function copyIndexCssToDist() {
  await new Promise((resolve) => {
    src("theme-chalk/index.css", { cwd: output }) //- 需要处理的css文件，放到一个字符串数组里
      .pipe(dest(outputDist))
  })
}

/**
 * [src/*.scss] to [es/*.scss, lib/*.scss]
 */
const buildScssCopy = async () => {
  await new Promise((resolve) => {
    src("**/*.scss", { cwd: pkgRoot })
      .pipe(dest(outputEsm))
      .pipe(dest(outputCjs))
      .on("end", resolve)
  })
}

/**
 * [src/**\/style/*.scss] to [es/**\/style/*.css, lib/**\/style/*.css]
 */
const buildScssModules = async () => {
  const sass = gulpSass(dartSass)
  await new Promise((resolve) => {
    src("**/style/*.scss", { cwd: pkgRoot })
      .pipe(sass.sync())
      .pipe(autoprefixer({ cascade: false }))
      .pipe(cleanCSS())
      .pipe(dest(outputEsm))
      .pipe(dest(outputCjs))
      .on("end", resolve)
  })
}

/**
 * [src/*.scss] to [dist/*.css]
 */
const buildScssFull = async () => {
  const sass = gulpSass(dartSass)
  await new Promise((resolve) => {
    src("*.scss", { cwd: pkgRoot })
      .pipe(sass.sync())
      .pipe(autoprefixer({ cascade: false }))
      .pipe(cleanCSS())
      .pipe(dest(output))
      .on("end", resolve)
  })
}

/**
 * [src/**\/style/*.ts] to [es/**\/style/*.js, lib/**\/style/*.js]
 */
const buildStyleModules = async () => {
  const input = [
    // style
    ...(await glob("**/theme-chalk/*.scss", {
      cwd: pkgRoot,
      absolute: true,
      onlyFiles: true,
    })),
    // resolver
    path.resolve(pkgRoot, "resolver.js"),
  ]

  const bundle = await rollup({
    input,
    plugins: [
      esbuild({
        sourceMap: false,
      }),
    ],
    external: [/./],
    treeshake: false,
  })

  await Promise.all([
    bundle.write({
      format: "esm",
      dir: outputEsm,
      exports: undefined,
      preserveModules: true,
      preserveModulesRoot: "src",
      sourcemap: true,
      entryFileNames: `[name].mjs`,
    }),
    bundle.write({
      format: "cjs",
      dir: outputCjs,
      exports: "named",
      preserveModules: true,
      preserveModulesRoot: "src",
      sourcemap: true,
      entryFileNames: `[name].js`,
      paths: generatePaths(),
    }),
  ])
}

export const buildStyle = async () => {
  await Promise.all([copyPackageAndPgMd(), copyThemeChalkSource(), buildScss()])
}
